<template>
	<view class="page">
		<view class="tabber_box">
			<view class="tabber_box_static" :style="{ height: `${getters.statusBarHeight}px` }"></view>
			<view class="tabber_box_flex" :style="{ height: `${getters.statusBarHeight}px` }"></view>
		</view>
		<view class="tabber_box_title_static">
		</view>
		<view class="tabber_box_title_flex" :style="{ top: `${getters.statusBarHeight}px` }">
			
			<view class="text">
				消息列表
			</view>
		</view>
		
		<view class="list" v-if="chat_list &&chat_list.length > 0">
			<view class="row" v-for='(row,index) in chat_list' :key='index' @click="onDetails(row,index)">
				<!-- 用户发的要显示店铺信息 -->
				<view class="left" v-if="row.gettype == 1">
					<image :src="row.shop_avatar" mode=""></image>
					<text class="icon" v-if='row.status == 0'></text>
				</view>
				<!-- 店铺发的要显示用户信息 -->
				<view class="left" v-if="row.gettype == 2">
					<image :src="row.user_avatar" mode=""></image>
					<text class="icon" v-if='row.status == 0'></text>
				</view>
				<view class="right">
					<view class="right_l" v-if="row.type == 1">
						<view class="">
							{{row.gettype == 2 ? row.user_name : row.shopping_name}}
						</view>
						<view class="">
							{{row.content_text ?row.content_text : '无最新消息' }}
						</view>
					</view>
					<view class="right_l" v-if="row.type == 2">
						<view class="">
							{{row.gettype == 2 ? row.user_name : row.shopping_name}}
						</view>
						<view class="">
							{{row.content_img ?row.content_img : '无最新消息' }}
						</view>
					</view>
					<view class="right_l" v-if="row.type == 3">
						<view class="">
							{{row.gettype == 2 ? row.user_name : row.shopping_name}}
						</view>
						<view class="">
							{{row.content_jjson ?'精算单' : '无最新消息' }}
						</view>
					</view>
					<view class="right_l" v-if="row.type == 4">
						<view class="">
							{{row.gettype == 2 ? row.user_name : row.shopping_name}}
						</view>
						<view class="">
							{{row.content_goods ?'商品信息' : '无最新消息' }}
						</view>
					</view>
					<view class="right_l" v-if="row.type == 5">
						<view class="">
							{{row.gettype == 2 ? row.user_name : row.shopping_name}}
						</view>
						<view class="">
							{{row.content_text ?row.content_text : '无最新消息' }}
						</view>
					</view>
					<view class="right_r">
						<!-- {{typeTime(row.created_at)}} -->
						{{row.created_at}}
					</view>
				</view>
			</view>
		</view>
		<empty v-else />
		<tabbar ref='tabbar' active='2'/>
	</view>
</template>

<script>
	import {conversation_get,chatrecord_add,chatrecord_get} from "./static/api.js"
	// // #ifdef H5
	// const ws = new WebSocket("wss://xiaoqu.wuguoxin.vip:8080");
	// //#endif
	
	import WS from "@/utils/WebSocket.js"
	import tabbar from '@/components/tabbar.vue'
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			tabbar
		},
		filters: {
			typeName(x, row) { //['text', 'audio', 'image', 'video'],
				return x == 'text' ? row.text : x == 'audio' ? '[语音]' : x == 'image' ? '[图片]' : x == 'video' ? '[视频]' :
					'[消息]'
			}

		},
		data() {
			return {
				lengthV: 0,
				chat_list:[],
				page: 1,
				pageSize: 30,
				
				ws: null,
				msg:'',
				socketOpen:false,
				socketMsgQueue: [],
				SocketTask:'',
			}
		},
		onPullDownRefresh(){
			this.page = 1
			this.onGetUsers()
		},
		methods: {
			typeTime(num) { //时间戳数据处理
				let date = new Date(num);
				let y = date.getFullYear();
				let MM = date.getMonth() + 1;
				MM = MM < 10 ? ('0' + MM) : MM; //月补0
				let d = date.getDate();
				d = d < 10 ? ('0' + d) : d; //天补0
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h; //小时补0
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m; //分钟补0
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s; //秒补0
				if (new Date(num).toDateString() === new Date().toDateString()) {
					return `${h}:${m}`
				} else {
					return `${y}/${MM}/${d}`
				}
			},
			async onGetUsers() {
				
				this.loading = true
				var res = await conversation_get({
					page: this.page,
					limit: this.pageSize
				})
				
				console.log(res,'会话记录')
				
				if(res.count > 0){
					this.chat_list = res.list.reverse()
					this.chat_list.forEach(row=>{
						
						console.log(row,'循环内')
						if(row.type == 3 ){
							row.content_jjson = JSON.parse(JSON.stringify(JSON.parse(row.content_jjson)))
						}
					})
					
					// this.chat_list.forEach((c, ci) => {
					// 	c.toAvatar = obj[ci].avatar
					// 	c.toNick = obj[ci].nick
					// 	c.content = obj[ci].nick
					// 	c.time = obj[ci].nick
					// })
					this.$store.commit('set_chat_list', this.chat_list)
					console.log(this.chat_list,'最终')
					this.lengthV = this.chat_list.length
					this.$forceUpdate()
				}
				
				
				uni.hideLoading()
				this.loading = false
				this.getUserOne()
				return;
				
				this.$IM.getUsers({
					accounts: this.chat_list.map(x => x.to),
					done: (err, obj) => {
						if (!err) {
							this.chat_list.forEach((c, ci) => {
								c.toAvatar = obj[ci].avatar
								c.toNick = obj[ci].nick
							})
							this.$store.commit('set_chat_list', this.chat_list)
							// console.log(this.chat_list)
							this.$forceUpdate()
						}
					}
				});
			},
			onDetails(row, index) {
				// if (row.to == 0) {
				// 	uni.showToast({
				// 		title: '暂未开通',
				// 		icon: 'none'
				// 	})
				// } else {
					// if (row.unread) {
					// 	this.chat_list[index].unread = 0
					// 	this.$store.commit('set_chat_list', this.chat_list)
					// }
					//判断是商家点进来的详情，还是用户点进来的gettype字段2代表商家1代表用户
					if(row.gettype == 2){
						this.$store.commit('set_chat_to', {
							id: row.users_id,
							name: row.user_name,
							shopping_id: row.shopping_id,
							avatar: row.user_avatar
						})
						uni.navigateTo({
							url: '/pagesChat/chatRoom?char_type=2&conversation_id='+row.conversation_id+'&shopping_id='+row.shopping_id+'&users_id='+row.users_id+'&chat_toname='+row.user_name
						})
					}else if(row.gettype == 1){
						this.$store.commit('set_chat_to', {
							id: row.shop_userid,
							name: row.shopping_name,
							shopping_id: row.shopping_id,
							avatar: row.shop_avatar
						})
						uni.navigateTo({
							url: '/pagesChat/chatRoom?char_type=1&conversation_id='+row.conversation_id+'&shopping_id='+row.shopping_id+'&users_id='+row.users_id+'&chat_toname='+row.shopping_name
						})
					}
					
				// }
				// if(row.type == 2){
				// 	uni.navigateTo({url:'/pagesChat/transactionLogistics?id=' + row.id})
				// }
				// else if(row.type == 0 ){
				// 	uni.navigateTo({url:`/pagesChat/chatRoom?id=${row.id}&title=${row.title}`})
				// }
				// else{

				// }
			},
			getUserOne(){
				// 发送数据
				// this.ws.webSocketSendMsg('发送信息')
				console.log(this.$store.getters.userInfo.accid,'用户ID');
				const msg = '{"code":"102","name":"用户名称","user_id":"'+this.$store.getters.userInfo.accid+'"}';
				//workerman链接并记录个人的ID
				this.ws.webSocketSendMsg(msg)
				// this.$IM.getUsers({
				// 	accounts: [this.chat_list[0].to],
				// 	done: (err, obj) => {
				// 		if (!err) {
				// 			this.$set(this.chat_list[0], 'toAvatar', obj[0].avatar)
				// 			this.$set(this.chat_list[0], 'toNick', obj[0].nick)
				// 		}
				// 	}
				// });
			},
		},
		onLoad() {
			
			// this.ws.closeSocket();
			this.ws = new WS(`wss://xiaoqu.wuguoxin.vip:8080`)  // xxx 表示接口地址URL
			
			// this.ws.initEventHandle();
			
			
			this.ws.getWebSocketMsg(data => {
				const dataJson = data;
				console.log('接收的消息从服务器消息列表', dataJson);
			    if(typeof(dataJson) == "object") {
			        console.log("wsObject", dataJson);
				}else {
			        console.log(dataJson);
					if(dataJson == "刷新消息"){
						this.onGetUsers();
					}
			    }
			});
			
			
			// if (this.chat_list.length) 
			
			
			// // #ifdef APP-PLUS ||  MP-WEIXIN
			
			// // this.SocketTask = uni.getStorageSync('SocketTask');
			// //连接connectSocket
			// this.SocketTask = uni.connectSocket({
			//   url:'wss://xiaoqu.wuguoxin.vip:8080',
			//   header: {
			//     'content-type': 'application/json'
			//   },
			//   protocols: [ 'protocol1'],
			//   timeout:60000,
			//   success: function (res) {
			//     console.log('Socket连接成功:', res);
			//   },
			//   fail: function (res) {
			//     console.error('连接失败:', res);
			//   },
			// })
			// // websocket打开
			// // uni.onSocketOpen(() => {
			// //   console.log('监听到 WebSocket 连接已打开！');
			  
			// // })
			
			// this.SocketTask.onOpen(function (res) {
			// 	console.log('监听到 WebSocket 连接已打开！');
			// 	this.socketOpen = true;
			// 	// for (var i = 0; i < this.socketMsgQueue.length; i++) {
			// 	// 	this.sendSocketMessage(this.socketMsgQueue[i]);
			// 	// }
			// 	// this.socketMsgQueue = [];
			// });
			
			// //连接失败
			// // uni.onSocketError((err) => {
			// //   console.log('websocket连接失败', err);
			// //   uni.connectSocket({
			// //     url:'wss://xiaoqu.wuguoxin.vip:8080',
			// //     header: {
			// //       'content-type': 'application/json'
			// //     },
			// //     protocols: [ 'protocol1'],
			// // 	timeout:60000,
			// //     success: function (res) {
			// //       console.log('Socket连接成功:', res);
			// //     },
			// //     fail: function (res) {
			// //       console.error('连接失败:', res);
			// //     },
			// //   })
			// // })
						 
			// // 收到websocket消息
			
			// this.SocketTask.onMessage(function (res) {
			// // wx.onSocketMessage(function (res) {
			// 	console.log(res.data,'收到服务端消息消息列表');
			// 	// console.log(this.$store.getters.userInfo.accid,'收到服务端消息22233：');
			// 	if(res.data == '刷新消息'){
			// 		this.onGetUsers()
			// 	}
			// 	// const msg = JSON.parse(res.data) // 收到的消息为字符串，需处理一下
			// 	// console.log(msg,'收到服务端消息33：');
			// })
			// // 检测到 WebSocket 连接
			// this.SocketTask.onError(function (res) {
			//   console.log(res,'监听到 WebSocket连接报错！');
			//   this.SocketTask = uni.connectSocket({
			//     url:'wss://xiaoqu.wuguoxin.vip:8080',
			//     header: {
			//       'content-type': 'application/json'
			//     },
			//     protocols: [ 'protocol1'],
			//     timeout:60000,
			//     success: function (res) {
			//       console.log('Socket连接成功:', res);
			//     },
			//     fail: function (res) {
			//       console.error('连接失败:', res);
			//     },
			//   })
			// })
			// // 检测到 WebSocket 连接已关闭
			// this.SocketTask.onClose(function (res) {
			//   console.log('监听到 WebSocket 连接已关闭！');
			// })
			// //#endif
			// // #ifdef H5
			
			// this.SocketTask = ws;
			// this.SocketTask.onmessage = function(e) {
			//     console.log("收到服务端的消息消息列表：" + e.data);
			// 	// console.log(this.$store.getters.userInfo.accid,'收到服务端消息22233：');
			// 	if(e.data == '刷新消息'){
			// 		this.onGetUsers()
			// 	}
			// };
			// this.SocketTask.onclose = function(e) {
			//     console.log("服务已断开2" );
			// }
			// //#endif
			
			
			this.onGetUsers()
			
			this.$store.commit('set_chat_commodityInfo', null)
		},
		watch: {
			length(x) {
				if (x > this.lengthV) {
					this.onGetUsers()
				}
				this.lengthV = x
			},
			chat_list: {
				handler:function(newValue, oldValue) {
					console.log(newValue,'监听消息变化')
					console.log(oldValue,'监听消息变化2')
					if (newValue.length !== oldValue.length) {
						this.onGetUsers()
						// this.$IM.getUsers({
						// 	account: this.chat_list[0].to,
						// 	done: (err, obj) => {
						// 		if (!err) {
						// 			this.$set(this.chat_list[0].toAvatar,'avatar',obj.avatar)
						// 			this.$set(this.chat_list[0].toNick,'avatar',obj.nick)
						// 		}
						// 	}
						// });
					}
				},
				deep:true
			}
		},
		computed: {
			...mapState(['chat_list']),
			length() {
				return  this.$store.state.chat_list ? this.$store.state.chat_list.length : 0
			}
		}

	}
</script>

<style lang="scss" scoped>
	.list {
		padding: 0 22rpx 0 38rpx;
		width: 100%;
		box-sizing: border-box;

		.row {
			width: 100%;
			padding: 40rpx 0;
			border-bottom: 2rpx solid #f6f7fb;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				position: relative;

				image {
					width: 104rpx;
					height: 104rpx;
					border-radius: 50%;
					background-color: #CCCCCC;
				}

				.icon {
					position: absolute;
					content: '';
					right: 0;
					top: 0;
					width: 16rpx;
					height: 16rpx;
					background: $theme;
					border-radius: 50%;
				}
			}

			.right {
				width: calc(100% - 122rpx);
				display: flex;
				justify-content: space-between;

				.right_l {
					width: calc(100% - 160rpx);

					>view:nth-child(1) {
						color: #222222;
						line-height: 40rpx;
						font-size: 28rpx;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					>view:nth-child(2) {
						margin-top: 8rpx;
						color: #ADADAD;
						line-height: 34rpx;
						font-size: 24rpx;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}

				.right_r {
					text-align: right;
					width: 150rpx;
					font-size: 24rpx;
					line-height: 34rpx;
					color: #ADADAD;
				}
			}
		}
	}
	
	
	.tabber_box .tabber_box_static {
		width: 100%;
		background-color: #fff;
	}
	
	.tabber_box .tabber_box_flex {
		width: 100%;
		background-color: #fff;
		position: fixed;
		z-index: 999;
		top: 0;
		left: 0;
	}
	
	.tabber_box_title_static {
		height: 80rpx;
		width: 100%;
		background-color: #fff;
	}
	
	.tabber_box_title_flex {
		background-color: #fff;
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		z-index: 99;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 42rpx;
		font-family: PingFang SC, PingFang SC-Semibold;
		font-weight: 700;
		text-align: center;
		color: #000000;
	}
	.tabber_box_title_flex .left {
			margin-top: 4rpx;
			position: absolute;
			left: 58rpx;
			top: 50%;
			transform: translateY(-50%);
	
			
		}
		
	.tabber_box_title_flex .left image{
		width: 36rpx;
		height: 36rpx;
	}
	
	.tabber_box_title_flex .left text{
		display: inline-block;
		position: absolute;
		left: 34rpx;
		top: 5px;
		width: 10rpx;
		height: 10rpx;
		background: $theme;
		border-radius: 50%;
	}
</style>
